<template>
  <Header :title="'注册'" />
  <div class="register">
    <div class="register_box">
      <div class="title">欢迎注册</div>
      <van-form label-position="top" @submit="submitForm">
        <van-cell-group inset>
          <van-field
            v-model="username"
            name="用户名"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <van-field
            v-model="confirmPassword"
            type="password"
            name="确认密码"
            label="确认密码"
            placeholder="确认密码"
            :rules="[{ validator: pwdIs, required: true, message: '前后密码不一致' }]"
          />
          <van-field
            v-model="mobile"
            type="number"
            name="手机号码"
            label="手机号码"
            placeholder="手机号码"
            :rules="[{ validator: validator, required: true, message: '请填写手机号码' }]"
          />
        </van-cell-group>
        <div style="display: flex; margin: 5px 32px">
          <span class="register_tap" @click="toLogin">已有账号？立即登录</span>
        </div>
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit"> 注册 </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
import { reactive, toRefs } from "vue";
import Header from "@/components/SHeader.vue";
import { getRegister } from "@/api/user";
import { useRouter } from "vue-router";
import { toast } from "@/util/toast";
export default {
  components: {
    Header,
  },
  setup() {
    const router = useRouter();
    const form = reactive({
      username: "",
      password: "",
      confirmPassword: "",
      mobile: "",
    });
    const submitForm = async () => {
      console.log(1111);
      getRegister({
        username: form.username,
        password: form.password,
        mobile: form.mobile,
      }).then((res) => {
        if (res.data.code == 400) {
          toast("fail", res.data.msg, 1000);
        } else {
          toast("success", res.data.msg, 500);
          router.push("/login");
        }
      });
    };
    const toLogin = () => {
      router.push("/login");
    };
    // 手机号码校验
    const validator = (val) => /^1[3-9]\d{9}$/.test(val);
    const pwdIs = (val) => val === form.password;
    return {
      ...toRefs(form),
      submitForm,
      toLogin,
      validator,
      pwdIs,
    };
  },
};
</script>
<style scoped>
.title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}

/* 页面背景色 */
.register {
  height: 100%;
}
.register_tap {
  text-align: left;
  cursor: pointer;
}
.register_box {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
}
</style>
